var entityCollection = require('../../../Base/server/controllers/EntityCollection');
var publicFun = require('../../../Base/server/controllers/Function');

//网关调用更新全部App
exports.updateApps = function(req, res) {
	var apps = req.body.Apps;
	var entity = entityCollection.getEntity("App");
	var datas = [];
	if(apps.length > 0){
		for (var i = 0, len = apps.length; i < len; i++) {
			datas.push({ 
				updateOne: {
					filter: { AppID: apps[i].AppID },
					update: { $set: apps[i] },
					upsert: true
				}
			});
		}

		entity.Entity.collection.bulkWrite(datas, {ordered: false}, function(err, data){
			if(err){
				res.json({
	                Error: err
	            });
			}
			else{
				res.json({
	                Data: data
	            });
			}
		});
	}
	else{
		res.json({
            Data: true
        });
	}
};

//根据请求用户，获取所有App信息
exports.getApps = function(req, res) {
	var gatewayAddress;
	publicFun.getSysParameterValue('GatewayServer', function(err, val){
		if(err){
			res.json({
                Error: err
            });
		}
		else{
			gatewayAddress = val;

			var entity = entityCollection.getEntity("User");
			entity.findOne({_id: req.User._id}, {
					path: 'AppRoles', 
					select: 'Apps', 
					populate: {
						path: 'Apps'
					}
				}, function(err, record){
				if(err){
					res.json({
		                Error: err
		            });
				}
				else{
					var apps = [];
					for(var i=0; i<record.AppRoles.length; i++){
						for(var j=0; j<record.AppRoles[i].Apps.length; j++){
							var isFind = false;
							for(var n=0; n<apps.length; n++){
								if(apps[n].AppID == record.AppRoles[i].Apps[j].AppID){
									isFind = true;
									break;
								}
							}
							if(!isFind){
								apps.push(record.AppRoles[i].Apps[j]);
							}
						}
					}
					
					res.json({
		                Data: {
		                	GatewayAddress: gatewayAddress,
		                	Apps: apps
		                }
		            });
				}
			});
		}
	});	
};
